<template>
  <div>
    <div class="clear"></div>
    <div class="concent">
      <!--地址 -->
      <div class="paycont">
        <div class="address">
          <h3>确认收货地址:</h3>
          <div class="control" style="margin-top:10px;margin-left: 100px">
            <div class="tc-btn createAddr theme-login am-btn am-btn-danger" @click="addUserAddr">使用新地址</div>
          </div>
          <div class="clear"></div>
          <ul>
            <template v-for="(userAddr,index) in userAddrs">
              <div class="per-border"></div>
              <li :class="{'user-addresslist':true,'defaultAddr':index==addrIndex}" @click="chooseAddr(index)">

                <div class="address-left">
                  <div class="user DefaultAddr">
                      <span class="buy-address-detail">
                        <span class="buy-user">{{ userAddr.receiverName }} </span>
                        <span class="buy-phone">{{ userAddr.receiverMobile }}</span>
                      </span>
                  </div>
                  <div class="default-address DefaultAddr">
                    <span class="buy-line-title buy-line-title-type">邮政编码：</span>
                    <span class="buy--address-detail">
                      <span class="province">{{ userAddr.postCode }}</span>
                    </span>
                  </div>
                  <div class="default-address DefaultAddr">
                    <span class="buy-line-title buy-line-title-type">收货地址：</span>
                    <span class="buy--address-detail">
                      <span class="province">{{ userAddr.province }}</span>省
                      <span class="city">{{ userAddr.city }}</span>市
                      <span class="dist">{{ userAddr.area }}</span>区
                      <span class="street">{{ userAddr.addr }}</span>
                    </span>

                  </div>

                  <ins class="deftip" v-if="userAddr.commonAddr==1">默认地址</ins>
                </div>
                <div class="address-right">
                  <a href="">
                    <span class="am-icon-angle-right am-icon-lg"></span></a>
                </div>
                <div class="clear"></div>

                <div class="new-addr-btn">
                  <a class="hidden" href="#">设为默认</a>
                  <span class="new-addr-bar hidden">|</span>
                  <a @click.stop="editUserAddr(userAddr)">编辑</a>
                  <span class="new-addr-bar">|</span>
                  <a @click.stop="delUserAddr(userAddr.addrId)">删除</a>
                </div>

              </li>
            </template>

          </ul>

          <div class="clear"></div>
        </div>
        <!--物流 -->
        <div class="logistics">
          <h3>选择物流方式:</h3>
          <ul class="op_express_delivery_hot">
            <li class="OP_LOG_BTN  " data-value="yuantong"><i class="c-gap-right"
                                                              style="background-position:0px -468px"></i>圆通<span></span>
            </li>
            <li class="OP_LOG_BTN  " data-value="shentong"><i class="c-gap-right"
                                                              style="background-position:0px -1008px"></i>申通<span></span>
            </li>
            <li class="OP_LOG_BTN  " data-value="yunda"><i class="c-gap-right"
                                                           style="background-position:0px -576px"></i>韵达<span></span>
            </li>
            <li class="OP_LOG_BTN op_express_delivery_hot_last " data-value="zhongtong"><i class="c-gap-right"
                                                                                           style="background-position:0px -324px"></i>中通<span></span>
            </li>
            <li class="OP_LOG_BTN  op_express_delivery_hot_bottom" data-value="shunfeng"><i class="c-gap-right"
                                                                                            style="background-position:0px -180px"></i>顺丰<span></span>
            </li>
          </ul>
        </div>
        <div class="clear"></div>

        <!--支付方式-->
        <div class="logistics">
          <h3>选择支付方式:</h3>
          <ul class="pay-list">
            <li :class="{'pay':true,'card':true,'selected':payType==0}" @click="changePayType(0)"><img
                src="@/assets/images/wangyin.jpg"/>银联<span></span></li>
            <li :class="{'pay':true,'qq':true,'selected':payType==1}" @click="changePayType(1)"><img
                src="@/assets/images/weizhifu.jpg"/>微信<span></span></li>
            <li :class="{'pay':true,'taobao':true,'selected':payType==2}" @click="changePayType(2)"><img
                src="@/assets/images/zhifubao.jpg"/>支付宝<span></span></li>
          </ul>
        </div>
        <div class="clear"></div>

        <!--订单 -->
        <div class="concent">
          <div id="payTable">
            <h3>确认订单信息:</h3>

            <div class="clear"></div>
            <div style="margin-top: 20px;border: 1px dashed #c8ced2;">
              <el-table
                  ref="multipleTable"
                  :data="tableData"
                  tooltip-effect="dark"
                  style="width: 100%"
                  stripe
                  :header-cell-style="{'color':'black','text-align':'center'}"
                  @selection-change="handleSelectionChange"
              >
                <el-table-column
                    label="商品信息"
                    width="250"
                    align="center">
                  <template slot-scope="scope">
                    <router-link :to="'/detail?pid='+scope.row.productId">
                      <div class="item-pic" style="float:left;">
                        <a href="#" target="_blank" data-title="美康粉黛醉美东方唇膏口红正品 持久保湿滋润防水不掉色护唇彩妆"
                           class="J_MakePoint" data-point="tbcart.8.12">
                          <img :src="scope.row.productImg" class="itempic J_ItemImg"
                               style="width: 80px;height:80px"></a>
                      </div>
                      <div class="item-info">
                        <div class="item-basic-info">
                          <a href="#" target="_blank" title="美康粉黛醉美唇膏 持久保湿滋润防水不掉色"
                             class="item-title J_MakePoint" data-point="tbcart.8.11">
                            {{ scope.row.productName }}
                          </a>
                        </div>
                      </div>
                    </router-link>
                  </template>
                </el-table-column>
                <el-table-column
                    label="规格"
                    width="250"
                    align="center">
                  <template slot-scope="scope">
                    <div class="item-props item-props-can">
                      <div class="sku-line" style="line-height: 90px">{{ scope.row.skuProps }}</div>
                      <span tabindex="0" class="btn-edit-sku theme-login">修改</span>
                      <i class="theme-login am-icon-sort-desc"></i>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    label="单价"
                    width="100"
                    align="center">
                  <template slot-scope="scope">
                    <div class="td-price">
                      <div class="item-price price-promo-promo">
                        <div class="price-content">
                          <div class="price-line">
                            <em class="price-original"
                                style="text-decoration: line-through;color: darkgray">￥{{
                                scope.row.originalPrice
                              }}</em>
                          </div>
                          <div class="price-line">
                            <em class="J_Price price-now" tabindex="0">￥{{ scope.row.sellPrice }}</em>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    label="数量"
                    width="130"
                    align="center">
                  <template slot-scope="scope">
                    <div class="amount-wrapper ">
                      <div class="item-amount ">
                        <div class="sl">
                          {{ scope.row.cartNum }}
                        </div>
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    label="金额"
                    width="100"
                    align="center">
                  <template slot-scope="scope">
                    <div class="td-inner">
                      <em tabindex="0" class="J_ItemSum number">￥{{ scope.row.sellPrice * scope.row.cartNum }}</em>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                    label="配送方式"
                    align="center">
                  <template slot-scope="scope">
                    <div class="td-inner">
                      <span>包邮</span>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="clear"></div>
          </div>
        </div>
        <div class="clear"></div>
        <div class="pay-total">
          <!--留言-->
          <div class="order-extra">
            <div class="order-user-info">
              <div id="holyshit257" class="memo">
                <label>买家留言：</label>
                <input class="memo-input J_MakePoint c2c-text-default memo-close" placeholder="选填,建议填写和卖家达成一致的说明"
                       title="选填,对本次交易的说明（建议填写已经和卖家达成一致的说明）"
                       type="text" v-model="orderRemark">
                <div class="msg hidden J-msg">
                  <p class="error">最多输入500个字符</p>
                </div>
              </div>
            </div>

          </div>
          <!--优惠券 -->
          <div class="clear"></div>
        </div>
        <!--含运费小计 -->
        <div class="buy-point-discharge ">
          <p class="price g_price ">
            合计（包邮） <span>¥</span><em class="pay-sum">{{ totalPrice }}</em>
          </p>
        </div>

        <!--信息 -->
        <div class="order-go clearfix">
          <div class="pay-confirm clearfix">
            <div class="box">
              <div id="holyshit267" class="realPay" tabindex="0"><em class="t">实付款：</em>
                <span class="price g_price ">
                  <span>¥</span> <em id="J_ActualFee" class="style-large-bold-red ">{{ totalPrice }}</em>
                </span>
              </div>

              <div id="holyshit268" class="pay-address">

                <p class="buy-footer-address">
                  <span class="buy-line-title buy-line-title-type">寄送至：</span>
                  <span class="buy--address-detail" v-if="userAddrs[addrIndex]">
								   <span class="province">{{ userAddrs[addrIndex].province }}</span>省
                    <span class="city">{{ userAddrs[addrIndex].city }}</span>市
                    <span class="dist">{{ userAddrs[addrIndex].area }}</span>区
                    <span class="street">{{ userAddrs[addrIndex].addr }}</span>
                  </span>
                </p>
                <p class="buy-footer-address">
                  <span class="buy-line-title">收货人：</span>
                  <span class="buy-address-detail" v-if="userAddrs[addrIndex]">
                    <span class="buy-user">{{ userAddrs[addrIndex].receiverName }} </span>
										<span class="buy-phone">{{ userAddrs[addrIndex].receiverMobile }}</span>
                  </span>
                </p>
              </div>
            </div>

            <div id="holyshit269" class="submitOrder">
              <div class="go-btn-wrap">
                <a id="J_Go" class="btn-go" tabindex="0" title="点击此按钮，提交订单" @click="submitOrder">提交订单</a>
              </div>
            </div>
            <div class="clear"></div>
          </div>
        </div>
      </div>

      <div class="clear"></div>
      <!--</div>-->
      <div class="footer">
        <div class="footer-hd">
          <p>
            <a href="#">恒望科技</a>
            <b>|</b>
            <a href="#">商城首页</a>
            <b>|</b>
            <a href="#">支付宝</a>
            <b>|</b>
            <a href="#">物流</a>
          </p>
        </div>
        <div class="footer-bd">
          <p>
            <a href="#">关于恒望</a>
            <a href="#">合作伙伴</a>
            <a href="#">联系我们</a>
            <a href="#">网站地图</a>
            <em>© 2015-2025 Hengwang.com 版权所有</em>
          </p>
        </div>
      </div>
    </div>
    <div class="theme-popover-mask"></div>
    <div class="theme-popover">

      <!--标题 -->
      <div class="am-cf am-padding">
        <div class="am-fl am-cf"><strong class="am-text-danger am-text-lg">新增地址</strong> / <small>Add address</small>
        </div>
      </div>
      <hr/>
      <!-- 对话框     -->

    </div>
    <el-dialog title="新增收货地址" :visible.sync="dialogFormVisible" width="500px">
      <el-form :model="form" ref="form" label-width="100px">
        <el-form-item label="收货人" prop="receiverName">
          <el-input v-model="form.receiverName" placeholder="请输入收货人姓名"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="receiverMobile">
          <el-input v-model="form.receiverMobile" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" prop="area">
          <el-select value="省一" placeholder="请选择省" style="width: 112px" v-model="form.province">
            <el-option label="省一" value="省一"></el-option>
            <el-option label="省二" value="省二"></el-option>
            <el-option label="省三" value="省三"></el-option>
          </el-select>
          <el-select value="市一" placeholder="请选择市" style="width: 112px;margin-left: 10px" v-model="form.city">
            <el-option label="市一" value="市一"></el-option>
            <el-option label="市二" value="市二"></el-option>
            <el-option label="市三" value="市三"></el-option>
          </el-select>
          <el-select value="区一" placeholder="请选择区" style="width: 112px;margin-left: 10px" v-model="form.area">
            <el-option label="区一" value="区一"></el-option>
            <el-option label="区二" value="区二"></el-option>
            <el-option label="区三" value="区三"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮政编码">
          <el-input v-model="form.postCode" placeholder="请输入邮政编码"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="addr">
          <el-input type="textarea" v-model="form.addr" placeholder="请输入详细地址"></el-input>
        </el-form-item>
        <el-form-item label="设为默认地址" prop="isDefault">
          <el-switch v-model="isDefault"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addAddress()">确 定</el-button>
      </div>
    </el-dialog>
    <div class="clear"></div>

  </div>
</template>

<script>
import {getUserAddrs, getOrderInfo, deleteUserAddr, updateOrAddUserAddr,addOrder} from '@/api/order'

export default {
  name: "OrderMain",
  props: ['cartIds'],
  data() {
    return {
      payType: 0,
      userAddrs: [],
      tableData: [],
      multipleSelection: [],
      total: 0,
      totalPrice: 0,
      addrIndex: 0,
      dialogFormVisible: false,
      orderRemark: '',
      form: {
        addrId: '',
        userId: '',
        receiverName: '',
        receiverMobile: '',
        province: '',
        city: '',
        area: '',
        addr: '',
        postCode: '',
        status: 1,
        commonAddr: 0
      },
      isDefault: false,
      formLabelWidth: '120px'

    }
  },
  created() {
    //根据用户id获取用户收货地址
    this.getUserAddrs();
    //根据cartIds查询订单信息
    this.getOrderInfo();
  },
  watch: {
    tableData: {
      deep: true,
      handler(newVal, oldVal) {
        //alert('改变了')
        this.totalPrice = 0;
        newVal.forEach(item => {
          this.totalPrice += item.sellPrice * item.cartNum;
        })
        console.log(this.totalPrice)
      }
    }
  },
  methods: {
    changePayType(index) {
      this.payType = index;
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (val == null) {
        this.totalPrice = 0;
      } else {
        this.totalPrice = 0;
        val.forEach((item) => {
          this.totalPrice += item.sellPrice * item.cartNum;
        })
      }
    },
    getUserAddrs() {
      getUserAddrs(this.$store.state.id).then(data => {
        const res = data.data;
        //console.log(JSON.stringify(res.data))
        if (res.success) {
          this.userAddrs = res.data;
          this.userAddrs.forEach((item, index) => {
            if (item.commonType == 1) {
              this.addrIndex = index;
            }
          })
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })
    },
    getOrderInfo() {
      getOrderInfo(this.cartIds).then(data => {
        const res = data.data;
        if (res.success) {
          this.tableData = res.data;
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })
    },
    chooseAddr(index) {
      this.addrIndex = index;
    },
    delUserAddr(addrId) {
      this.$confirm('确定删除该收货地址吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserAddr(addrId).then(data => {
          const res = data.data;
          if (res.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }
          this.addrIndex = 0;
          this.getUserAddrs();
        }).catch(error => {
          this.$message({
            message: error,
            type: 'error'
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    addUserAddr() {
      this.form.receiverName = '';
      this.form.receiverMobile = '';
      this.form.province = '';
      this.form.city = '';
      this.form.area = '';
      this.form.addr = '';
      this.isDefault = false;
      this.form.userId = '';
      this.form.addrId = '';
      this.dialogFormVisible = true;
    },
    editUserAddr(userAddr) {
      this.form = userAddr;
      this.dialogFormVisible = true;
    },


    addAddress() {
      this.form.userId = this.$store.state.id;
      if (this.isDefault) {
        this.form.commonAddr = 1;
      } else {
        this.form.commonAddr = 0;
      }
      console.log(JSON.stringify(this.form))
      this.dialogFormVisible = false;
      updateOrAddUserAddr(this.form).then(
          data => {
            const res = data.data;
            if (res.success) {
              this.$message({
                message: '添加或更新成功',
                type: 'success'
              });
              this.getUserAddrs();
              this.form.receiverName = '';
              this.form.receiverMobile = '';
              this.form.province = '';
              this.form.city = '';
              this.form.area = '';
              this.form.addr = '';
              this.isDefault = false;
              this.form.userId = '';
              this.form.addrId = '';
            }
          }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })

    },
    submitOrder() {
      //将订单信息提交到添加订单接口
      //准备订单数据
      var cartIds = this.cartIds + '';
      var address = this.userAddrs[this.addrIndex].province + this.userAddrs[this.addrIndex].city + this.userAddrs[this.addrIndex].area + this.userAddrs[this.addrIndex].addr;
      var orders = {
        "actualAmount": this.totalPrice,
        "orderRemark": this.orderRemark,
        "payTime": "",
        "payType": 0,
        "receiverAddress":address,
        "receiverMobile": this.userAddrs[this.addrIndex].receiverMobile,
        "receiverName":this.userAddrs[this.addrIndex].receiverName,
        "totalAmount": this.totalPrice,
        "userId": this.$store.state.id
      }
      //提交订单
      addOrder(cartIds,orders).then(data => {
        const res = data.data;
        console.log(JSON.stringify(res.data));
        if (res.success) {
          this.$message({
            message: '提交成功',
            type: 'success'
          });
          //跳转到支付页面
          this.$router.replace('/pay?orderInfo=' + JSON.stringify(res.data)+'&payStatus=1');
        }
      }).catch(error => {
        this.$message({
          message: error,
          type: 'error'
        });
      })
    }


  }
}
</script>

<style scoped>
a:hover {
  cursor: pointer;
}
</style>